/*
 * Copyright (C) 2007-2008 SlideMe client
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.slideme.android.manager.download.impl;

import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;
import org.slideme.android.manager.ContentHandler;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * A service for downloading of Android applications.
 */
public final class AndroidContentHandler implements ContentHandler {

    private Context context;

    /**
     * Returns mime-type: application/x-android
     */
    public String getMimeType() {
        return "application/x-android";
    }

    /**
     * @see ContentHandler#init(android.content.Context) 
     */
    public void init(Context context) {
        if(context == null) {
            throw new IllegalArgumentException("context");
        }
        this.context = context;
    }

    /**
     * @see ContentHandler#download(java.net.URI, String, android.content.pm.PackageManager)
     */
    public void download(URI uri, String fileName, PackageManager packageManager) throws IOException {
        if (uri == null) {
            throw new IllegalArgumentException("AndroidContentHandler.download:uri");
        }
        if (packageManager == null) {
            throw new IllegalArgumentException("AndroidContentHandler.download:packageManager");
        }
        if (fileName == null) {
            throw new IllegalArgumentException("AndroidContentHandler.download:fileName");
        }

        Log.d("AndroidContentHandler", "Opening connection for android application: URI = " + uri);

        URI serverUri;
        try {
            serverUri = new URI(uri.toString().replaceAll("&amp;", "&"));
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("contentURI:" + e.getMessage());
        }
        URL url = serverUri.toURL();
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        Log.d("AndroidContentHandler", "Attempting to download application: File Name = " + "/data/misc/" + fileName);
        FileOutputStream outputStream = new FileOutputStream("/data/misc/" + fileName);
        InputStream is = null;
        try {
            is = connection.getInputStream();
            byte[] buffer = new byte[8192];
            int n;
            while ((n = is.read(buffer)) >= 0) {
                outputStream.write(buffer, 0, n);
            }
        } finally {
            try {
                if (is != null) is.close();
                outputStream.close();
            } catch (IOException e) {

            }
        }

       // Log.i("AndroidContentHandler", "Installing android application: File Name = " + fileName);
      //  packageManager.installPackage(Uri.parse(("file:///data/misc/" + fileName)));
        Log.i("AndroidContentHandler", "Sucessfully installed android application: File Name = " + fileName);
    }
}
